package admin_admin

import (
	"gitee.com/theegg/go-brick/app/controller/admin_api"
	"gitee.com/theegg/go-brick/app/model/admin/admin_users"
	"gitee.com/theegg/go-brick/app/service/app"
	"github.com/gin-gonic/gin"
	"strconv"
)

// @title GetTargetAdminUserFromParams
// @description 内置方法　通过参数id获取目标对象, 验证当前 登陆用户 是否可以操作 目标用户
func GetTargetAdminUserFromParams(c *gin.Context) (*admin_users.AdminUsers, error) {
	id := c.PostForm("id")
	if id == "" {
		return nil, app.NewError("对不起, 管理员ID不能为空")
	}

	int64Id, errConv := strconv.ParseInt(id, 10, 64)
	if errConv != nil {
		return nil, app.NewError("对不起, 目标用户ID格式不正确")
	}

	// 获取用户
	targetUser, errTarget := admin_users.GetItemFromCacheById(int64Id)
	if errTarget != nil {
		return nil, app.NewError(errTarget)
	}

	// 判定目标用户是否是当前用户的直接下级
	currentAdminUser, errCurrent := admin_api.GetLoginAdminUser(c)
	if errCurrent != nil {
		return nil, app.NewError(errCurrent)
	}

	ok, errChild := currentAdminUser.HaveChild(targetUser.Id)
	if errChild != nil {
		return nil, app.NewError(errChild)
	}

	if !ok {
		return nil, app.NewError("对不起, 您不具有修改目标用户密码的权限!")
	}

	return targetUser, nil
}
